<template>
    <div v-loading="isLoading || isExporting" class="meter-report-container">
        <!-- 日期选择和导出区域 -->
        <div class="meter-report-header">
            <CustomDatePicker width="14rem" border round v-model="dateRange" />
            <div style="margin-left:auto;">
                <span style="font-size: var(--font-size-small);margin-right: var(--gap-small);">表格布局</span>
                <el-segmented class="custom-style" v-model="tableSize" :options="sizeOptions" />
            </div>
            <!-- 新增刷新按钮 -->
            <el-button type="primary" :loading="isLoading" @click="handleRefresh">
                <template #icon>
                    <i class="fa fa-refresh"></i>
                </template>
                刷新
            </el-button>
            <el-button type="success" :loading="isExporting" @click="handleExport">
                <template #icon>
                    <i class="fa fa-download"></i>
                </template>
                导出
            </el-button>
        </div>

        <!-- 表格区域 - 修改为使用shouldRenderTable控制渲染 -->
        <vxe-table v-if="shouldRenderTable" :row-config="{ isCurrent: true, isHover: true }" :size="tableSize"
            :style="{ fontSize: getFontSize() }" ref="tableRef" height="92%" border align="center"
            :data="meterTableData" :tree-config="treeConfig" :export-config="exportConfig" :column-config="columnConfig"
            :resizable-config="resizableConfig" :element-loading-text="isExporting ? '正在导出所有数据请稍等...' : '加载中...'">
            <!-- 固定列 -->
            <vxe-column tree-node fixed="left" field="meter_code" title="表计编号" width="140" />
            <vxe-column fixed="left" :width="getCellWidth('area')" show-overflow="tooltip" title="供应点位">
                <template #default="{ row }">
                    {{ row.supply_region || '-' }}
                </template>
            </vxe-column>
            <vxe-column :width="getCellWidth()" show-overflow="tooltip" field="installation_location" title="安装位置" />
            <vxe-column field="specification" :width="getCellWidth('spec')" title="规格" />
            <!-- 启读数 -->
            <vxe-column :width="getCellWidth()" field="startReading" title="启读数">
                <template #default="{ row }">
                    {{ formatReadingValue(row.startReading, row.startError) }}
                </template>
            </vxe-column>
            <!-- 动态日期列 -->
            <vxe-colgroup v-for="(date, dateIndex) in dateColumns" :key="date" :title="date">
                <vxe-column :width="getCellWidth()" :field="`usage_${dateIndex}`" title="用量">
                    <template #default="{ row }">
                        {{ formatFlowValue(row[`usage_${dateIndex}`], row[`error_${dateIndex}`]) }}
                    </template>
                </vxe-column>
                <vxe-column :width="getCellWidth()" :field="`reading_${dateIndex}`" title="读数">
                    <template #default="{ row }">
                        {{ formatReadingValue(row[`reading_${dateIndex}`], row[`error_${dateIndex}`]) }}
                    </template>
                </vxe-column>
            </vxe-colgroup>
            <!-- 总用量列 -->
            <vxe-column fixed="right" field="sum" :width="getCellWidth()" title="总用量">
                <template #default="{ row }">
                    {{ formatFlowValue(row.sum) }}
                </template>
            </vxe-column>
        </vxe-table>

        <!-- 子表对话框 -->
        <SubMeterDialog v-model:visible="dialogVisible" :meter-data="selectedMeterData" :date-columns="dateColumns"
            :table-size="tableSize" :fetch-data="fetchAndProcessMeterData" :load-child-nodes="loadChildNodes" />
    </div>
</template>
<script setup>
import { ref, onMounted, watch, computed, reactive, nextTick } from "vue";
import { handleError } from "@/utils/handleError";
import dayjs from "dayjs";
import { getMeterReportApi, getMeterInfoApi } from "@/api/meter";
import CustomDatePicker from "@/components/header/CustomDatePicker.vue";
import { useCompanyStore } from "@/stores/company";
import { formatFlowValue, formatReadingValue, generateDateColumns, transformMeterData, sortMeterList } from "@/utils/meterUtils";
import SubMeterDialog from '../components/SubMeterDialog.vue';
import { useIntelligentMeter } from "../../../../../composables/useIntelligentMeter";
import convertToTreeData from '@/utils/convertToTreeData';
import { getMetersByLevel } from '@/utils/getMetersByLevel';
import * as XLSX from 'xlsx';
import { generateTimeConfig } from "@/utils/date.js";

// 表格布局配置
const sizeOptions = [
    { label: '紧凑', value: 'mini' },
    { label: '标准', value: 'small' },
    { label: '宽松', value: 'medium' }
];

let tableSize = ref('small');
// 添加控制表格渲染的状态变量
const shouldRenderTable = ref(true);

// 新增：表计列表相关状态
const treeDataForChart = ref([]);
const meterList = ref([]);
const meterLevels = ref([]);
const currentMeter = ref(null);
const currentSelectedType = ref(2); // 电表类型

// 获取表计列表
async function fetchMeterList(params = {}) {
    params = {
        type: currentSelectedType.value,
        ...params
    };
    try {
        isLoading.value = true;
        const res = await getMeterInfoApi(params);
        if (res.code !== 200) {
            throw new Error(res.message || '获取表计列表失败');
        }
        // 对列表进行排序
        meterList.value = sortMeterList(res.data);
        treeDataForChart.value = await convertToTreeData(meterList.value);
        meterLevels.value = getMetersByLevel(treeDataForChart.value);
        return res;
    } catch (error) {
        handleError(error, '获取表计列表失败');
        return { code: 500, data: [] };
    } finally {
        isLoading.value = false;
    }
}

const getFontSize = () => {
    switch (tableSize.value) {
        case 'mini':
            return '12px';
        case 'medium':
            return '18px';
        default:
            return '14px';
    }
};

// 获取单元格宽度
const getCellWidth = (type) => {
    switch (tableSize.value) {
        case 'mini':
            return type === 'area' ? 80 : type === 'spec' ? 60 : 60;
        case 'medium':
            return type === 'area' ? 120 : type === 'spec' ? 140 : 140;
        default:
            return type === 'area' ? 100 : type === 'spec' ? 100 : 100;
    }
};

// 表格配置
const columnConfig = reactive({
    resizable: true
});

const resizableConfig = reactive({
    dragMode: 'fixed'
});

// 状态管理
const companyStore = useCompanyStore();

// 组件引用
const tableRef = ref(null);
const tableTimeConfig = generateTimeConfig('monthly', 0) || { start_time: 0, end_time: 0 }
// 响应式数据
const dateRange = ref([
    tableTimeConfig.start_time,  // 月初
    tableTimeConfig.end_time     // 月末或今天的时间(根据generateTimeConfig的逻辑)
]);

const dialogVisible = ref(false);
const selectedMeterData = ref(null);
const meterTableData = ref([]);
const isLoading = ref(false);
const isExporting = ref(false);
const Exported = ref(false);

// 计算导出文件名（包含时间）
const getExportFileName = () => {
    if (!dateRange.value || !dateRange.value[0]) {
        return '电表日统计报表';
    }

    const startDate = dayjs(dateRange.value[0]);
    const endDate = dayjs(dateRange.value[1]);
    return `电表日统计报表_${startDate.format('YYYY年MM月DD日')}_${endDate.format('MM月DD日')}`;
};

// 导出配置
const exportConfig = computed(() => ({
    type: 'xlsx',
    includeFooter: true,
    useStyle: true,
    isFooter: true,
    isColgroup: true,
    isAllExpand: true,
    filename: getExportFileName(),
    sheetName: '表计报表',
    modes: ['current'],
    original: false  // 导出渲染后的数据而不是原始数据
}));

// 树形配置
const treeConfig = reactive({
    transform: true,
    rowField: "id",
    parentField: "parent_id",
    lazy: true,
    hasChild: "hasChild",
    showLine: true,
    loadMethod: ({ row }) => loadChildNodes(row),
    toggleMethod({ expanded, row }) {
        if (isExporting.value) return true;
        if (row && row.level === 2) {
            dialogVisible.value = true;
            selectedMeterData.value = row;
            return false;
        }
        return true;
    },
    iconOpen: 'vxe-icon-square-minus',
    iconClose: 'vxe-icon-square-plus'
});

// 计算属性：日期列
const dateColumns = computed(() => {
    if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) {
        return [];
    }
    return generateDateColumns(dateRange.value[0], dateRange.value[1]);
});

// 获取并处理表计数据
async function fetchAndProcessMeterData(meter) {
    if (!meter || !meter.id) {
        console.warn('无效的表计数据:', meter);
        return null;
    }

    if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) {
        console.warn('日期范围无效');
        return null;
    }

    try {
        const response = await getMeterReportApi({
            id: meter.id,
            start_time: dateRange.value[0],
            end_time: dateRange.value[1],
            interval: 'day',
        });

        // 检查响应数据
        if (!response) {
            console.warn(`获取表计${meter.meter_code}的数据返回为空`);
            return null;
        }

        return transformMeterData(meter, response);
    } catch (error) {
        handleError(error, `获取表计${meter.meter_code}的数据失败`);
        return null;
    }
}

// 加载子节点数据
async function loadChildNodes(parentNode) {
    if (!parentNode || !parentNode.customChildren) {
        console.warn('父节点无效或缺少子节点数据');
        return [];
    }

    try {
        // 检查customChildren是否为数组
        if (!Array.isArray(parentNode.customChildren)) {
            console.warn('父节点的customChildren不是数组:', parentNode.customChildren);
            return [];
        }

        const promises = parentNode.customChildren.map(child => {
            if (!child) return Promise.resolve(null);
            return fetchAndProcessMeterData(child);
        });

        const children = await Promise.all(promises);
        return children.filter(Boolean);
    } catch (error) {
        handleError(error, '加载子节点数据失败');
        return [];
    }
}

const { scrollToLatest } = useIntelligentMeter({
    tableRef,
})

// 获取表计报表数据
async function fetchMeterReport() {
    if (isLoading.value) return;

    try {
        meterTableData.value = [];
        isLoading.value = true;

        // 日期变化时，触发表格重新渲染
        shouldRenderTable.value = false;
        await nextTick();
        shouldRenderTable.value = true;

        // 检查表计数据 - 修改：使用本地状态而不是store
        if (!treeDataForChart.value || !Array.isArray(treeDataForChart.value)) {
            console.warn('表计树数据无效');
            isLoading.value = false;
            return;
        }

        const meters = treeDataForChart.value;
        if (!meters || !Array.isArray(meters)) {
            console.warn('查找表计数据失败');
            isLoading.value = false;
            return;
        }

        const promises = meters.map(meter => {
            if (!meter) return Promise.resolve(null);
            return fetchAndProcessMeterData(meter);
        });

        const results = await Promise.all(promises);
        meterTableData.value = results.filter(Boolean);

        // 先结束加载状态
        isLoading.value = false;

        // 确保表格完全渲染
        await nextTick();
        // 然后执行表格操作
        const table = tableRef.value;
        if (table) {
            try {
                await table.setAllTreeExpand(true);
                await scrollToLatest();
            } catch (error) {
                console.warn('展开树节点或滚动失败:', error);
            }
        } else {
            console.warn('表格引用不存在');
        }
    } catch (error) {
        handleError(error, '获取电表数据失败');
        // 设置一个空的表格数据以防止界面出错
        meterTableData.value = [];
    } finally {
        isLoading.value = false;
    }
}

// 新增刷新功能处理方法
async function handleRefresh() {
    try {
        // 重置Exported状态，确保下次导出时能重新展开节点
        Exported.value = false;

        // 显示刷新提示
        ElMessage({
            type: 'info',
            title: '提示',
            message: '正在刷新数据...',
            duration: 2000
        });

        // 重新获取表计数据
        await fetchMeterReport();

        // 刷新成功提示
        ElMessage({
            type: 'success',
            title: '成功',
            message: '数据刷新成功',
            duration: 2000
        });
    } catch (error) {
        handleError(error, '数据刷新失败', true);
    }
}

// 创建Excel表头结构
function createExcelHeaders() {
    const headers = [];
    const mergeRanges = [];

    // 第一行表头（主要列标题）
    const firstRow = [
        '表计编号', '供应点位', '安装位置', '规格', '启读数'
    ];

    // 添加动态日期列
    dateColumns.value.forEach(date => {
        firstRow.push(date, ''); // 每个日期占两列（用量和读数）
    });

    firstRow.push('总用量');
    headers.push(firstRow);

    // 第二行表头（子列标题）
    const secondRow = [
        '', '', '', '', '' // 前5列空白
    ];

    // 为每个日期添加用量和读数子标题
    dateColumns.value.forEach((date, index) => {
        secondRow.push('用量', '读数');

        // 记录需要合并的单元格范围（日期列）
        const colIndex = 5 + index * 2; // 5是前面固定列的数量
        mergeRanges.push({
            s: { r: 0, c: colIndex }, // 开始位置
            e: { r: 0, c: colIndex + 1 } // 结束位置
        });
    });

    secondRow.push('');
    headers.push(secondRow);

    return { headers, mergeRanges };
}

// 格式化数据行
function formatDataRow(row, rowIndex) {
    const dataRow = [
        row.meter_code || '',
        row.supply_region || '-',
        row.installation_location || '',
        row.specification || '',
        formatReadingValue(row.startReading, row.startError)
    ];

    // 添加动态日期列数据
    dateColumns.value.forEach((date, dateIndex) => {
        // 用量列
        const usageValue = row[`usage_${dateIndex}`];
        const errorValue = row[`error_${dateIndex}`];
        const formattedUsage = formatFlowValue(usageValue, errorValue);
        dataRow.push(formattedUsage);

        // 读数列
        const readingValue = row[`reading_${dateIndex}`];
        const formattedReading = formatReadingValue(readingValue, errorValue);
        dataRow.push(formattedReading);
    });

    // 总用量
    dataRow.push(formatFlowValue(row.sum));

    return dataRow;
}

// 获取所有表计数据（展平树形结构）
async function getAllMeterDataFlat() {
    const allData = [];

    // 递归获取所有节点数据
    async function collectNodeData(nodes, level = 1) {
        for (const node of nodes) {
            if (!node) continue;

            // 添加当前节点
            allData.push({
                ...node,
                level: level
            });

            // 获取子节点数据
            if (node.hasChild && node.customChildren) {
                const childrenData = await loadChildNodes(node);
                if (childrenData && childrenData.length > 0) {
                    await collectNodeData(childrenData, level + 1);
                }
            }
        }
    }

    // 开始收集所有表计数据
    await collectNodeData(meterTableData.value);

    return allData;
}

// 主导出函数
async function handleExport() {
    try {
        isExporting.value = true;

        ElMessage({
            type: 'info',
            message: '正在准备导出数据...',
        });

        // 1. 获取所有表计数据（展平）
        const allMeterData = await getAllMeterDataFlat();

        // 2. 创建Excel表头
        const { headers, mergeRanges } = createExcelHeaders();

        // 3. 创建工作簿和工作表
        const workbook = XLSX.utils.book_new();

        // 4. 准备数据
        const sheetData = [...headers];

        // 添加表计数据
        allMeterData.forEach((row, index) => {
            const dataRow = formatDataRow(row, index);
            sheetData.push(dataRow);
        });

        // 5. 创建工作表
        const worksheet = XLSX.utils.aoa_to_sheet(sheetData);

        // 6. 设置列宽
        const columnWidths = [
            { wch: 20 }, // 表计编号
            { wch: 12 }, // 供应点位
            { wch: 15 }, // 安装位置
            { wch: 10 }, // 规格
            { wch: 12 }, // 启读数
        ];

        // 为动态日期列设置宽度
        dateColumns.value.forEach(() => {
            columnWidths.push({ wch: 12 }); // 用量列
            columnWidths.push({ wch: 12 }); // 读数列
        });

        columnWidths.push({ wch: 12 }); // 总用量列

        worksheet['!cols'] = columnWidths;

        // 7. 设置合并单元格
        if (mergeRanges.length > 0) {
            worksheet['!merges'] = mergeRanges;
        }

        // 8. 添加工作表到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet, '电表日统计报表');

        // 9. 生成文件名
        const startDate = dayjs(dateRange.value[0]).format('YYYY年MM月DD日');
        const endDate = dayjs(dateRange.value[1]).format('MM月DD日');
        const fileName = `电表日统计报表_${startDate}_${endDate}.xlsx`;

        // 10. 导出文件
        XLSX.writeFile(workbook, fileName);

        ElMessage({
            type: 'success',
            message: '导出成功！',
        });

    } catch (error) {
        console.error('导出失败:', error);
        ElMessage({
            type: 'error',
            message: '导出失败，请重试',
        });
        handleError(error, '导出失败');
    } finally {
        isExporting.value = false;
    }
}

// 监听数据变化 - 修改：使用本地状态而不是store
watch(
    [() => dateRange.value, () => treeDataForChart.value],
    () => {
        if (treeDataForChart.value && treeDataForChart.value.length > 0) {
            fetchMeterReport();
        }
    },
    { deep: true }
);

// 监听公司改变
watch(
    () => companyStore.currentCompany,
    async (newCompany) => {
        if (newCompany) {
            try {
                // 重置Exported状态
                Exported.value = false;

                // 重新获取表计列表
                await fetchMeterList();

                // 重新获取数据
                await fetchMeterReport();
            } catch (error) {
                handleError(error, '切换公司失败');
            }
        }
    }
);

// 生命周期钩子
onMounted(async () => {
    try {
        // 确保设置为电表类型
        currentSelectedType.value = 2;

        // 获取表计列表
        await fetchMeterList();

        // 获取表计数据
        await fetchMeterReport();
    } catch (error) {
        handleError(error, "初始化失败");
    }
});
</script>

<style scoped>
.meter-report-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.meter-report-header {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
}

:deep(.custom-style) {
    --el-border-radius-round: 20px;
}
</style>